<?php
/**
 * Name
 * 2018/11/5
 * ╔═════╗                 ╔═╗ ╔═╗
 * ║ ╔═══╝                 ║ ║ ║ ║
 * ║ ╚═══╦══╦══╦═════╦═════╣ ╚═╝ ║
 * ╚═══╗ ║  ║  ║  ║  ║  ║  ╠═╗ ╔═╝
 * ╔═══╝ ║  ║  ║  ║  ║  ║  ║ ║ ║
 * ╚═════╩═════╩══╩══╩══╩══╝ ╚═╝
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\Adminer;

class LoginController extends Controller
{
    public function login()
    {
        if (Auth::guard('admin')->check()) {
            return redirect('/admin/index');
        }

        if (View::exists('Admin/login')) {
            return view('Admin/login');
        } else {
            return 'View Not Found';
        }
    }

    public function loginPost(Request $request)
    {
        $input = $request->all();
        $rule = [
            'username' => 'required|string|max:255',
            'password' => 'required|string',
            'captcha' => 'required|captcha',
        ];
        $message = [
            'username.required' => '用户名不能为空',
            'password.required' => '密码不能为空',
            'captcha.required' => '验证码不能为空',
            'captcha.captcha' => '请输入正确的验证码',
        ];
        $validate = Validator::make($input, $rule, $message);
        //$validate->validate();
        if (!$validate->passes()) {
            return back()->withErrors($validate);
        }
        //dd(33);
        $loginStatus = Auth::guard('admin')->attempt([
            'username' => $request->input('username'),
            'password' => $request->input('password'),
            'status' => 1,
        ], $request->has('remember'));
        if ($loginStatus) {
            $user = Auth::guard('admin')->user();
            $loginnum = $user->loginnum;
            $user->increment('loginnum');
            if ($loginnum == 0) {
                return redirect('/admin/index')->with('go', '/admin/adminer/updatepwd');
            }
            return redirect('/admin/index');
        } else {
            $request->flash();
            return redirect('/admin/login')->with('error', '账号密码错误');
        }
    }

    public function logout()
    {
        AUth::guard('admin')->logout();
        return redirect('admin/login');
    }


}